package com.example.testapp.activity.activity.study;

import android.content.Intent;
import android.os.Bundle;
import android.support.annotation.Nullable;
import android.text.TextUtils;
import android.util.Xml;
import android.view.View;
import android.view.ViewGroup;
import android.widget.AdapterView;
import android.widget.BaseAdapter;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.ListView;
import android.widget.RelativeLayout;
import android.widget.TextView;

import com.example.testapp.R;
import com.example.testapp.activity.activity.SuperActivity;
import com.example.testapp.activity.http.AsyncHttpUtil;
import com.example.testapp.activity.http.Contacts;
import com.example.testapp.activity.model.NewsItem;
import com.example.testapp.activity.util.DateUtils;
import com.example.testapp.activity.util.LogUtil;
import com.example.testapp.activity.view.ErrorHintView;
import com.example.testapp.activity.view.listview.PullToRefreshAdapterViewBase;
import com.example.testapp.activity.view.listview.PullToRefreshBase;
import com.example.testapp.activity.view.listview.PullToRefreshListView;
import com.loopj.android.http.AsyncHttpResponseHandler;
import com.squareup.picasso.Picasso;

import org.xmlpull.v1.XmlPullParser;
import org.xmlpull.v1.XmlPullParserException;

import java.io.ByteArrayInputStream;
import java.io.IOException;
import java.util.ArrayList;
import java.util.List;

import cz.msebera.android.httpclient.Header;

/**
 * Created by l on 2016/9/1.
 */
public class NewsFocusActivity extends SuperActivity {

    private PullToRefreshListView mListView;
    private ErrorHintView   mHintView;

    private int pageNext = 1;
    private boolean flag = false;
    private List<NewsItem> mList = new ArrayList<>();
    private NewsFocusAdapter mAdapter;

    private LinearLayout footerView;

    public static int VIEW_LIST = 1;
    /**显示断网**/
    public static int VIEW_WIFIFAILUER = 2;
    /** 显示加载数据失败 **/
    public static int VIEW_LOADFAILURE = 3;
    public static int VIEW_LOADING = 4;

    @Override
    protected void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.layout_news_cusfo);
        getWindow().setBackgroundDrawable(null);
        initView();
    }

    private void initView() {
        RelativeLayout headView = (RelativeLayout) this.findViewById(R.id.head);
        headView.findViewById(R.id.back_left).setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                finish();
            }
        });
        TextView title = (TextView) headView.findViewById(R.id.head_title);
        title.setText("焦点新闻");

        mListView = (PullToRefreshListView) this.findViewById(R.id.focus_list);
        mHintView = (ErrorHintView) this.findViewById(R.id.focus_hintView);

        initPullList();
        showLoading(VIEW_LOADING);
        loadNewsFocusInfo(true);
    }

    private void initPullList() {
        mAdapter = new NewsFocusAdapter();
        mListView.setAdapter(mAdapter);
        mListView.setOnRefreshListener(new PullToRefreshBase.OnRefreshListener<ListView>() {
            @Override
            public void onRefresh(PullToRefreshBase<ListView> refreshView) {
                if (refreshView.isHeaderShown()){
                    defParams();
                    loadNewsFocusInfo(true);
                }
            }
        });
        mListView.setOnItemClickListener(new AdapterView.OnItemClickListener() {
            @Override
            public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
                NewsItem item = mList.get(position - 1);
                Intent intent = new Intent(mContext, NewsDetailActivity.class);
                Bundle bundle = new Bundle();
                bundle.putSerializable("item", item);
                intent.putExtras(bundle);
                startActivity(intent);
            }
        });
        mListView.setOnPreRefreshingAnimListener(new PullToRefreshAdapterViewBase.OnPreRefreshingAnimListener() {
            @Override
            public void onPreRefreshingAnim() {
               mListView.setFooterLoadingViewHeaderText("加载更多博客");
            }
        });
        mListView.setOnLastItemVisibleListener(new PullToRefreshBase.OnLastItemVisibleListener() {
            @Override
            public void onLastItemVisible() {
                if (pageNext < 12){
                    flag = false;
                    loadNewsFocusInfo(false);
                }else{
                    mListView.onRefreshComplete();
                    if (footerView == null){
                        footerView = (LinearLayout) View.inflate(mContext, R.layout.item_pull_to_refresh_footer, null);
                        TextView footer = (TextView) footerView.findViewById(R.id.footer);
                        footer.setText("\"到底了呢-共\" + mList.size() + \"条资讯\"");
                        mListView.getRefreshableView().addFooterView(footerView);
                    }
                }
            }
        });
    }

    private void defParams() {
        pageNext = 1;
        flag = false;
    }

    private void showLoading(int i) {
       mHintView.setVisibility(View.GONE);
        mListView.setVisibility(View.GONE);

       switch (i){
           case 1:
               mHintView.hideLoading();
               mListView.setVisibility(View.VISIBLE);
               break;
           case 2:
               mHintView.hideLoading();
               mHintView.netError(new ErrorHintView.OperateListener() {
                   @Override
                   public void operate() {
                       defParams();
                       showLoading(VIEW_LOADING);
                       loadNewsFocusInfo(true);
                   }
               });
               break;
           case 3:
               mHintView.hideLoading();
               mHintView.loadFailure(new ErrorHintView.OperateListener() {
                   @Override
                   public void operate() {
                       defParams();
                       showLoading(VIEW_LOADING);
                       loadNewsFocusInfo(true);
                   }
               });
               break;
           case 4:
               mHintView.loadingdata();
               break;
       }
    }

    private void loadNewsFocusInfo(final boolean show) {
        String url = Contacts.FOCUS_PATH + pageNext + "/10";

        AsyncHttpUtil.get(url, new AsyncHttpResponseHandler() {
            @Override
            public void onSuccess(int statusCode, Header[] headers, byte[] responseBody) {
                if (footerView != null){
                    mListView.getRefreshableView().removeFooterView(footerView);
                    footerView = null;
                }
                mListView.onRefreshComplete();
                try {
                    showLoading(VIEW_LIST);
                    if (show){
                        mList.clear();
                    }
                    ByteArrayInputStream bis = new ByteArrayInputStream(responseBody);
                    parseNewsFocusXml(bis);
                    mAdapter.notifyDataSetChanged();
                    pageNext++;
                }catch (Exception e){
                    e.printStackTrace();
                    LogUtil.d("error", "hots news XmlPullParserException error");
                    showLoading(VIEW_LOADFAILURE);
                }
            }
            @Override
            public void onFailure(int statusCode, Header[] headers, byte[] responseBody, Throwable error) {
                 showLoading(VIEW_WIFIFAILUER);
            }
        });
    }

    /**
     * 解析新闻焦点
     * @param bis
     * @throws IOException
     * @throws XmlPullParserException
     */
    private void parseNewsFocusXml(ByteArrayInputStream bis) throws XmlPullParserException, IOException {
        XmlPullParser parser = Xml.newPullParser();
        parser.setInput(bis, "UTF-8");
        int event = parser.getEventType();
        NewsItem item = null;

        while (event != XmlPullParser.END_DOCUMENT){
            switch (event){
                case XmlPullParser.START_DOCUMENT:
                    break;
                case XmlPullParser.START_TAG:
                    if ("entry".equals(parser.getName())){
                        flag = true;
                        item = new NewsItem();
                    }
                    if (flag){
                        if ("id".equals(parser.getName())){
                            String id = parser.nextText();
                            item.setId(id);
                        }else if ("title".equals(parser.getName())){
                            String title = parser.nextText();
                            item.setTitle(title);
                        }else if ("summary".equals(parser.getName())){
                            String summary = parser.nextText();
                            item.setSummary(summary);
                        }else if ("published".equals(parser.getName())){
                            String published = parser.nextText();
                            item.setPublished(published);
                        }else if ("updated".equals(parser.getName())){
                            String updated = parser.nextText();
                            item.setUpdated(updated);
                        }else if ("link".equals(parser.getName())){
                             String link = parser.nextText();
                             item.setLink(link);
                        }else if ("diggs".equals(parser.getName())){
                              String diggs = parser.nextText();
                            item.setDiggs(diggs);
                        }else if ("views".equals(parser.getName())){
                              String views = parser.nextText();
                            item.setViews(views);
                        }else if ("comments".equals(parser.getName())){
                              String comments = parser.nextText();
                            item.setComments(comments);
                        }else if ("topicIcon".equals(parser.getName())){
                               String topicIcon = parser.nextText();
                            item.setTopicIcon(topicIcon);
                        }else if ("sourceName".equals(parser.getName())){
                              String sourceName = parser.nextText();
                            item.setSourceName(sourceName);
                        }
                    }
                    break;
                case XmlPullParser.TEXT:
                    break;
                case XmlPullParser.END_TAG:
                     if ("entry".equals(parser.getName())){
                         mList.add(item);
                     }
                    break;
            }
            event = parser.next();
        }
    }

    public class NewsFocusAdapter extends BaseAdapter{

        @Override
        public int getCount() {
            return mList.size();
        }

        @Override
        public Object getItem(int position) {
            return mList.get(position);
        }

        @Override
        public long getItemId(int position) {
            return position;
        }

        @Override
        public View getView(int position, View convertView, ViewGroup parent) {
            ViewHolder holder = null;
            if (convertView == null){
                convertView = View.inflate(mContext, R.layout.view_item_news_focus, null);
                holder = new ViewHolder();
                holder.title = (TextView) convertView.findViewById(R.id.title);
                holder.published = (TextView) convertView.findViewById(R.id.sourceName);
                holder.diggsTv = (TextView) convertView.findViewById(R.id.diggs_tx);
                holder.sourceName = (TextView) convertView.findViewById(R.id.sourceName);
                holder.commentsTv = (TextView) convertView.findViewById(R.id.comments);
                holder.image = (ImageView) convertView.findViewById(R.id.image);
                convertView.setTag(holder);
            }else{
                holder = (ViewHolder) convertView.getTag();
            }

            NewsItem item = mList.get(position);

            holder.title.setText(item.getTitle());
            holder.sourceName.setText("" + item.getSourceName());

            if (!TextUtils.isEmpty(item.getTopicIcon())){
                Picasso.with(mContext).load(item.getTopicIcon()).placeholder(R.color.ECECEC).error(R.color.ECECEC).into(holder.image);
            }
            if (!TextUtils.isEmpty(item.getPublished())){
                holder.published.setText(DateUtils.convertGMTToLoacale(item.getPublished()));
            }
            if (!TextUtils.isEmpty(item.getComments())){
                holder.commentsTv.setText("评论" + item.getComments());
            }else{
                holder.commentsTv.setText("");
            }
            if (!TextUtils.isEmpty(item.getDiggs())){
                holder.diggsTv.setText(item.getDiggs());
            }else{
                holder.diggsTv.setText("");
            }
            return convertView;
        }

        public class ViewHolder{
            TextView title;
            TextView published;
            TextView diggsTv;
            TextView sourceName;
            TextView commentsTv;
            ImageView image;
        }
    }

    @Override
    protected void obtainInfo() {

    }
}
